package com.congee02.sw.var;

public class TotalFruit {

    public int totalFruit(int[] nums) {

        final int m = 2;

        int n = nums.length;

        int[] hash = new int[n + 1];

        // l = r = 0
        hash[nums[0]] ++;
        int sz = 1;
        int ans = 1;

        int l = 0;
        for (int r = 1 ; r < n ; r ++ ) {
            if (hash[nums[r]] ++ == 0) {
                sz ++;
            }
            while (sz > m) {
                hash[nums[l]] --;
                if (hash[nums[l ++]] == 0) {
                    sz --;
                }
            }
            ans = Math.max(ans, r - l + 1);
        }
        return ans;
    }

}
